package com.tamir.template.express.handle;

import com.tamir.template.bean.TNode;
import com.tamir.template.context.TemplateContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : tanggh
 * @description :〈描述〉
 * @date : 2016/10/31
 */
public class DefaultAttrValueHandle extends AbstractExpressValueHandle
{
    /**
     * 获取当前的值
     *
     * @param node
     * @param context
     * @return
     */
    @Override
    public Object getObject(TNode node, TemplateContext context) throws Exception
    {
        Object inputObj = getInputObject(node, context);
        String ex = node.getRealExpress().replaceAll("\\s+", "");
        String[] attributes = ex.split("\\.");
        Object obj = getObjectWithAttrsAndInputObj(attributes, inputObj, node.getInputKey(), ex);

        return obj;
    }



    /**
     * 生成文本
     * @param node
     * @param context
     * @return
     * @throws Exception
     */
    @Override
    public String generateText(TNode node, TemplateContext context) throws Exception
    {
        Object text = this.getObject(node, context);
        return text == null ? "" : String.valueOf(text);
    }

    public static void main(String[] args)
    {
        DefaultAttrValueHandle handle = new DefaultAttrValueHandle();
        String[] attribute = new String[]{"test", "parentNode", "outKey"};
//        ITNode rootNode = new ITNode();
//        rootNode.setOutKey("parent node out key");
//        ITNode node = new ITNode();
//        node.setParentNode(rootNode);
//        node.setOutKey("sub node out key");
//        try
//        {
//            String[] attributeSub = new String[]{"", "outKey"};
//            System.out.println(handle.invokeMethod(node, attribute, 1));
//            System.out.println(handle.invokeMethod(node, attributeSub, 1));
//        }
//        catch (Exception e)
//        {
//            e.printStackTrace();
//        }
        Map<String, String> user = new HashMap<String,String>();
        user.put("key", "it's a test");
        System.out.println(handle.getInputObject("user['key']", user));
        System.out.println(handle.getInputObject("user[0]", attribute));

    }
}
